package io.finer.erp.jeecg.finance.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.CalendarUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import io.finer.erp.jeecg.bas.entity.BasBankAccount;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMeasureUnit;
import io.finer.erp.jeecg.bas.entity.BasSupplier;
import io.finer.erp.jeecg.bas.service.IBasBankAccountService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMeasureUnitService;
import io.finer.erp.jeecg.bas.service.IBasSupplierService;
import io.finer.erp.jeecg.bas.service.impl.ZrkDeliverEntryServiceImpl;
import io.finer.erp.jeecg.finance.dto.FinaFurlDTO;
import io.finer.erp.jeecg.finance.dto.FinaFurlEntryDTO;
import io.finer.erp.jeecg.finance.dto.FinaFurlSumDTO;
import io.finer.erp.jeecg.finance.dto.FinaPaymentDto;
import io.finer.erp.jeecg.finance.dto.PaymentStatisticDTO;
import io.finer.erp.jeecg.finance.dto.ReceiveDTO;
import io.finer.erp.jeecg.finance.entity.FinaFurl;
import io.finer.erp.jeecg.finance.entity.FinaFurlEntry;
import io.finer.erp.jeecg.finance.entity.FinaPayment;
import io.finer.erp.jeecg.finance.entity.FinaPaymentEntryLk;
import io.finer.erp.jeecg.finance.mapper.FinaNvoiceMapper;
import io.finer.erp.jeecg.finance.mapper.FinaPaymentMapper;
import io.finer.erp.jeecg.finance.service.IFinaFurlEntryService;
import io.finer.erp.jeecg.finance.service.IFinaFurlService;
import io.finer.erp.jeecg.finance.service.IFinaPaymentEntryLkService;
import io.finer.erp.jeecg.finance.service.IFinaPaymentService;
import io.finer.erp.jeecg.finance.vo.CGDIoBillFKVo;
import io.finer.erp.jeecg.finance.vo.FinaFurlVO;
import io.finer.erp.jeecg.finance.vo.FinaPaymentAddVo;
import io.finer.erp.jeecg.finance.vo.FinaPaymentPage;
import io.finer.erp.jeecg.finance.vo.FinaPaymentPageSum;
import io.finer.erp.jeecg.finance.vo.FinaPaymentSumPage;
import io.finer.erp.jeecg.finance.vo.FinaReceiptSumVO;
import io.finer.erp.jeecg.finance.vo.PaymentVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.service.IErpSysUserService;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;

/**
 * @Description: 付款表
 * @Author: jeecg-boot
 * @Date:   2021-03-22
 * @Version: V1.0
 */
@Service
public class FinaPaymentServiceImpl extends ServiceImpl<FinaPaymentMapper, FinaPayment> implements IFinaPaymentService {

    @Autowired
    private FinaPaymentMapper finaPaymentMapper;
    @Autowired
    private IBasSupplierService supplierService;
    @Autowired
    private IStkIoBillService ioBillService;
    @Autowired
    private IStkIoBillEntryService entryService;
    @Autowired
    private IErpSysUserService userService;
    @Autowired
    private  IBasMaterialService materialService;
    @Autowired
    private  IBasMaterialCategoryService materialCategoryService;
    @Autowired
    private IFinaFurlService  finaFurlService;
    @Autowired
	private FinaNvoiceMapper finaNvoiceMapper;
    @Autowired
    private ISysBaseAPI sysBasApi;
    @Autowired
    private IBasMeasureUnitService unitService;
    @Autowired
    private IFinaFurlEntryService furlEntryService;
    @Autowired
    private IFinaPaymentEntryLkService lkService;
    @Autowired
    private IBasBankAccountService accountService;


    @Override
    public List<FinaPaymentPage> getPayment(FinaPaymentPage finaPayment){
    	List<FinaPaymentPage> finaReceiptPage= finaPaymentMapper.getPaymentPage(finaPayment.getCreateTimeStart(),finaPayment.getCreateTimeEnd(),finaPayment.getSupplierName(),
        		finaPayment.getReceivablesEnd(),finaPayment.getReceivablesStart(),
        		finaPayment.getReceivedsEnd(),finaPayment.getReceivedsStart(),
        		finaPayment.getDiscountSumPriceStart(),finaPayment.getDiscountSumPriceEnd(),
        		finaPayment.getInvoicePriceStart(),finaPayment.getInvoicePriceEnd());
        //已开票金额
//        List<FinaNvoice> finaNvoiceList = finaNvoiceMapper.getSumInvoiceAndSupplierId(finaPayment.getCreateTimeStart(), finaPayment.getCreateTimeEnd());
//    	Map<String, BigDecimal> map = Maps.newHashMap();
//    	if(finaNvoiceList!=null&&finaNvoiceList.size()>0) {
//    		for(FinaNvoice finaNvoice:finaNvoiceList) {
//    			//每个供应商对应的开票金额
//    			map.put(finaNvoice.getSupplierId(), finaNvoice.getInvoicePrice());
//    		}
//    	}
        for (FinaPaymentPage record : finaReceiptPage) {
            FinaPaymentPage receiptPage = this.finaPaymentMapper.getTotalOwed(record.getSupplierId(), finaPayment.getSupplierName(), finaPayment.getCreateTimeStart());
            FinaPaymentPage receiptNone = this.finaPaymentMapper.getNoneInvoice(record.getSupplierId(), finaPayment.getSupplierName(), finaPayment.getCreateTimeStart());
            BigDecimal total = BigDecimal.ZERO;//期初欠款
        	BigDecimal noneInvoice = BigDecimal.ZERO;//期初未开票
        	BigDecimal fkPrice = BigDecimal.ZERO;//期初付款
            if (receiptPage != null) {
            	fkPrice = receiptPage.getPaids();
            	if(oConvertUtils.isNotEmpty(receiptPage.getTotalOwed())) {
            		total = receiptPage.getTotalOwed().subtract(fkPrice);
            	}
                record.setTotalOwed(total);//期初欠款
                if(receiptNone!=null) {
                	if(oConvertUtils.isNotEmpty(receiptPage.getTotalOwed()) 
                    		&& oConvertUtils.isNotEmpty(receiptNone.getCumulativeNoneInvoice())) {
                    	//期初未开票=期初货款金额(需开票)-期初开票金额
                    	noneInvoice = receiptPage.getNoneInvoicePrice().subtract(receiptNone.getCumulativeNoneInvoice());
                	}
                }
            }
            record.setCumulativeNoneInvoice(noneInvoice);//期初未开票
            BigDecimal dues = record.getDues()==null?BigDecimal.ZERO:record.getDues();//货单金额
            //货款金额(需开票)
            BigDecimal invoice = record.getNoneInvoicePrice()==null?BigDecimal.ZERO:record.getNoneInvoicePrice();
            BigDecimal paids = record.getPaids()==null?BigDecimal.ZERO:record.getPaids();//已付金额
            //当前月开票金额
            BigDecimal invoicePrice = record.getInvoicePrice()==null?BigDecimal.ZERO:record.getInvoicePrice();
            record.setInvoicePrice(invoicePrice);
            BigDecimal decimal = invoice.add(noneInvoice).subtract(invoicePrice);
            record.setNoneInvoicePrice(decimal);//期末未开票金额
            String sumPrice = "0";//折扣金额
            if(oConvertUtils.isNotEmpty(record.getDiscountSumPrice())) {
            	sumPrice = record.getDiscountSumPrice();
            }
            record.setDiscountSumPrice(sumPrice);
            BigDecimal bal = record.getDues().add(total).subtract(paids).subtract(new BigDecimal(sumPrice));
//            if(bal.compareTo(BigDecimal.ZERO)<0){
//                bal=BigDecimal.ZERO;
//            }
            record.setBalance(bal);//应收余额
//            record.setBalance(record.getPaids().subtract(record.getDues()));
//            record.setNoneInvoicePrice(record.getPaids().subtract(record.getInvoicePrice()));
            
        }
        
        String field = finaPayment.getColumn();
        String order = finaPayment.getOrder();
        if(StringUtils.equals(field, "totalOwed")) {
        	if(org.apache.commons.lang3.StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getTotalOwed));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getTotalOwed).reversed());
            }
        }else if(StringUtils.equals(field, "cumulativeNoneInvoice")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getCumulativeNoneInvoice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getCumulativeNoneInvoice).reversed());
            }
        }else if(StringUtils.equals(field, "dues")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getDues));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getDues).reversed());
            }
        }else if(StringUtils.equals(field, "paids")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getPaids));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getPaids).reversed());
            }
        }else if(StringUtils.equals(field, "discountSumPrice")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getDiscountSumPrice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getDiscountSumPrice).reversed());
            }
        }else if(StringUtils.equals(field, "balance")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getBalance));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getBalance).reversed());
            }
        }else if(StringUtils.equals(field, "invoicePrice")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getInvoicePrice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getInvoicePrice).reversed());
            }
        }else if(StringUtils.equals(field, "noneInvoicePrice")) {
        	if(StringUtils.equals(order, "asc")) {
        		finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getNoneInvoicePrice));
            }else if(StringUtils.equals(order, "desc")) {
            	finaReceiptPage.sort(Comparator.comparing(FinaPaymentPage::getNoneInvoicePrice).reversed());
            }
        }
        return finaReceiptPage;
    }

    @Override
    public  FinaPaymentPageSum getPageReceiptSum(
            String createTimeStart, String createTimeEnd,
            String supplierName,
            BigDecimal receivablesEnd,
            BigDecimal receivablesStart,
            BigDecimal receivedsEnd,BigDecimal receivedsStart,
            BigDecimal invoicePriceStart,BigDecimal invoicePriceEnd,
            BigDecimal discountSumPriceStart,BigDecimal discountSumPriceEnd) {

    	List<FinaPaymentPage> finaReceiptPagePage = finaPaymentMapper.getPaymentPage(createTimeStart,
									                createTimeEnd, supplierName,
									                receivablesEnd,receivablesStart,
									                receivedsEnd,receivedsStart,
									                discountSumPriceStart,discountSumPriceEnd,
									                invoicePriceStart,invoicePriceEnd);

        BigDecimal qc = new BigDecimal("0");
        BigDecimal hk = new BigDecimal("0");
        BigDecimal sk = new BigDecimal("0");
        BigDecimal qk = new BigDecimal("0");
        BigDecimal ye = new BigDecimal("0");

        FinaPaymentPageSum sumPage=new FinaPaymentPageSum();
        for (FinaPaymentPage record : finaReceiptPagePage) {
            FinaPaymentPage receiptPage = finaPaymentMapper.getTotalOwed(record.getSupplierId(), supplierName, createTimeStart);
            BigDecimal total = BigDecimal.ZERO;//期初欠款
        	BigDecimal fkPrice = BigDecimal.ZERO;//期初付款
            if (receiptPage != null) {
            	fkPrice = receiptPage.getPaids();
            	if(oConvertUtils.isNotEmpty(receiptPage.getTotalOwed())) {
            		total = receiptPage.getTotalOwed().subtract(fkPrice);
            	}
                record.setTotalOwed(total);//期初欠款
            }
//            BigDecimal decimal = record.getDues().add(record.getCumulativeNoneInvoice()).subtract(record.getInvoicePrice());
         
//            record.setNoneInvoicePrice(decimal);//未开票金额
            BigDecimal bal = record.getDues().add(record.getTotalOwed()).subtract(record.getPaids()).subtract(new BigDecimal(record.getDiscountSumPrice()));
            record.setBalance(bal);//应收余额

            qc = qc.add(total);
            hk = hk.add(record.getDues());
            sk = sk.add(record.getPaids());
            ye = ye.add(record.getBalance());
            qk = qk.add(new BigDecimal(record.getDiscountSumPrice()));

        }
        sumPage.setTotalOwed(qc);
        sumPage.setDues(hk);
        sumPage.setPaids(sk);
        sumPage.setDiscountSumPrice(qk);
        sumPage.setBalance(ye.subtract(qk));
        return sumPage;
    }




    @Override
    public Page<FinaPaymentSumPage> getSumPayment(IPage<FinaPaymentSumPage> page,String createTimeStart, String createTimeEnd, String supplierName){
        Page<FinaPaymentSumPage> finaReceiptPage= finaPaymentMapper.getPaymentSumPage(page,createTimeStart,createTimeEnd,supplierName);

        return finaReceiptPage;
    }

    @Override
    public boolean marchFlat(FinaPayment finaPayment) {
        //查询该客户下的所有应收或已收部分的帐单
        LambdaQueryWrapper<FinaPayment> wrapper = new LambdaQueryWrapper<FinaPayment>();
        wrapper.eq(FinaPayment::getSupplierId, finaPayment.getSupplierId());
        wrapper.eq(FinaPayment::getBillType, 3);
        wrapper.gt(FinaPayment::getPrice, 0);
        List<FinaPayment> receipts = list(wrapper);
        if (receipts != null && receipts.size() > 0) {
            BigDecimal s = finaPayment.getPrice();
            for (FinaPayment receipt : receipts) {
                s = s.subtract(receipt.getPrice());
                if (s.compareTo(BigDecimal.ZERO) < 0) {
                    //如果已收减去应收小于零。则将已收减去。
                    receipt.setPrice(s.setScale(2, BigDecimal.ROUND_DOWN).abs());
                    updateById(receipt);
                    break;
                } else if (s.compareTo(BigDecimal.ZERO) > 0) {
                    //如果已收减去应收大于0，则将应收改为平账并且继续对其他应收进行平账
                    receipt.setPrice(BigDecimal.ZERO);
                    updateById(receipt);
                } else {
                    //如果已收减去应收大于0，则将应收改为平账并且继续对其他应收进行平账
                    receipt.setPrice(BigDecimal.ZERO);
                    updateById(receipt);
                    break;
                }
            }
        }
        return true;
    }

    @Override
    @Transactional
    public void createPayable(StkIoBill stkIoBill, List<StkIoBillEntry> stkIoBillEntryList) {
        BigDecimal amt = new BigDecimal(0);
        List<FinaFurlEntry> entries=Lists.newArrayList();
        for(StkIoBillEntry entry : stkIoBillEntryList) {
        	FinaFurlEntry furlEntry = new FinaFurlEntry();
            amt = amt.add(entry.getSettleAmt());
            BasMaterial material=materialService.getById(entry.getMaterialId());
            BasMaterialCategory category = materialCategoryService.getById(material.getCategoryId());
            furlEntry.setProductId(category.getId());
            furlEntry.setProductName(category.getName());
            furlEntry.setProductCode(category.getCode());
            furlEntry.setMaterialId(material.getId());
            furlEntry.setModel(material.getModel());
            furlEntry.setRemark(material.getRemark());
            furlEntry.setUnitPrice(entry.getSettlePrice());
            BasMeasureUnit unit=unitService.getById(entry.getUnitId());
            furlEntry.setUnit(unit.getName());
            furlEntry.setQty(entry.getQty());
            furlEntry.setTotalPrice(entry.getSettleAmt());
            furlEntry.setSalesType("0");
            furlEntry.setPayStatus("0");
            furlEntry.setPayAmount(BigDecimal.ZERO);
            entries.add(furlEntry);

        }

        FinaPayment finaPayment=new FinaPayment();
        String suppName="";
        if(StringUtils.isNotBlank(stkIoBill.getSupplierId())){
            finaPayment.setSupplierId(stkIoBill.getSupplierId());
            BasSupplier basSupplier=supplierService.getById(stkIoBill.getSupplierId());
            if(basSupplier != null){
                suppName=basSupplier.getName();
                finaPayment.setSupplierName(suppName);
            }
        }
        String code = this.sysBasApi.getNoByCode("fh_no");
        finaPayment.setCode(code);
        finaPayment.setBillNo(stkIoBill.getSourceNo());
        finaPayment.setPrice(amt);
        finaPayment.setNoneInvoicePrice(amt);
        finaPayment.setBillType("3");//应付
//        save(finaPayment);

        FinaFurl finaFurl = new FinaFurl();
        finaFurl.setSupplierId(stkIoBill.getSupplierId());
        finaFurl.setSupplierName(suppName);
        finaFurl.setShippingDate(stkIoBill.getBillDate());
        String name=userService.getUserNameByPhone(stkIoBill.getHandlerId());
        finaFurl.setMaker(name);
        finaFurl.setSalesType("0");
        finaFurl.setTotalAmount(amt);
        finaFurl.setIoBillNo(stkIoBill.getBillNo());
        String capitalPrice = "0";
        if(oConvertUtils.isNotEmpty(amt)) {
        	capitalPrice = ZrkDeliverEntryServiceImpl.toChinese(amt.toString());
        }
        finaFurl.setCapitalPrice(capitalPrice);
        finaFurl.setCode(stkIoBill.getSourceNo());
        finaFurl.setRemark(stkIoBill.getRemark());
        finaFurl.setIsInvoice(stkIoBill.getIsInvoice());
        finaFurlService.saveMain(finaFurl, entries);
    }

    @Override
    public List<FinaPaymentDto> getPaymentEx(String createTimeStart, String createTimeEnd, String supplierName){
        List<FinaPaymentDto> finaReceipt= finaPaymentMapper.getPaymentSumExcel( createTimeStart,createTimeEnd,supplierName);
        for (FinaPaymentDto record : finaReceipt) {
            record.setBalance(record.getPaids().subtract(record.getDues()));
            record.setNoneInvoicePrice(record.getPaids().subtract(record.getInvoicePrice()));
        }
        return finaReceipt;
    }

    @Override
    public  FinaReceiptSumVO getamountFK(){
        return finaPaymentMapper.getamountFK();
    }



    @Override
    public List<CGDIoBillFKVo> getCGDIoBill(CGDIoBillFKVo ioBillFKVo){
        LambdaQueryWrapper<StkIoBill> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StkIoBill::getStockIoType,"601");
        wrapper.ne(StkIoBill::getHxStatus,"2");
        wrapper.eq(StkIoBill::getSupplierId,ioBillFKVo.getSupplierId());
        List<StkIoBill> lists=ioBillService.list(wrapper);
        List<CGDIoBillFKVo> vos= Lists.newArrayList();
        for (StkIoBill ioBill : lists) {
            LambdaQueryWrapper<StkIoBill> queryWrapperr=new LambdaQueryWrapper<>();
            queryWrapperr.eq(StkIoBill::getStockIoType,"101");
            queryWrapperr.eq(StkIoBill::getSourceId,ioBill.getId());
            List<StkIoBill> list=ioBillService.list(queryWrapperr);
            CGDIoBillFKVo cgdIoBillFKVo=new CGDIoBillFKVo();
            BigDecimal de=new BigDecimal("0");
            for (StkIoBill stkIoBill : list) {
                LambdaQueryWrapper<StkIoBillEntry> query=new LambdaQueryWrapper<>();
                query.eq(StkIoBillEntry::getMid,stkIoBill.getId());
                List<StkIoBillEntry> entries=entryService.list(query);
                BigDecimal decimal=new BigDecimal("0");
                for (StkIoBillEntry entry : entries) {
                    decimal=decimal.add(entry.getSettleAmt());
                }
                de=de.add(decimal);
                cgdIoBillFKVo.setBillNo(ioBill.getBillNo());
                cgdIoBillFKVo.setId(ioBill.getId());
                cgdIoBillFKVo.setRemark(ioBill.getRemark());
                cgdIoBillFKVo.setOrderMoney(decimal);
                cgdIoBillFKVo.setOrderTime(ioBill.getBillDate());
                cgdIoBillFKVo.setAccumulatedPrice(de);
                cgdIoBillFKVo.setHxPrice(de);
                cgdIoBillFKVo.setHxStatus(ioBill.getHxStatus());
                vos.add(cgdIoBillFKVo);
            }
        }
        return vos;
    }

    @Override
    public boolean automaticWriteOff(FinaPaymentAddVo paymentAddVo) {
        BigDecimal dec=BigDecimal.ZERO;
        if (paymentAddVo.getList() != null && paymentAddVo.getList().size() > 0) {
            for (CGDIoBillFKVo cgdIoBillFKVo : paymentAddVo.getList()) {
                String id = cgdIoBillFKVo.getId();
                    LambdaQueryWrapper<StkIoBill> queryWrapperr = new LambdaQueryWrapper<>();
                    queryWrapperr.eq(StkIoBill::getStockIoType, "101");
                    queryWrapperr.eq(StkIoBill::getSourceId, id);
                    List<StkIoBill> list = ioBillService.list(queryWrapperr);
                    for (StkIoBill stkIoBill : list) {
                        LambdaQueryWrapper<StkIoBillEntry> query = new LambdaQueryWrapper<>();
                        query.eq(StkIoBillEntry::getMid, stkIoBill.getId());
                        List<StkIoBillEntry> entries = entryService.list(query);
                        BigDecimal decimal = new BigDecimal("0");
                        for (StkIoBillEntry entry : entries) {
                            decimal = decimal.add(entry.getSettleAmt());
                        }
                       dec= paymentAddVo.getPrice().subtract(decimal);
                        StkIoBill ioBill=new StkIoBill();
                        if(dec.compareTo(BigDecimal.ZERO) > 0){
                            ioBill.setId(paymentAddVo.getId());
                            ioBill.setHandlerId("2");
                            ioBill.setHxPrice(dec.toString());
                            ioBillService.updateById(ioBill);
                        }else if(dec.compareTo(BigDecimal.ZERO) < 0){
                            ioBill.setId(paymentAddVo.getId());
                            ioBill.setHandlerId("1");
                            ioBill.setHxPrice(dec.toString());
                            ioBillService.updateById(ioBill);
                            break;
                        }else{
                            ioBill.setId(paymentAddVo.getId());
                            ioBill.setHandlerId("2");
                            ioBill.setHxPrice(dec.toString());
                            ioBillService.updateById(ioBill);
                            break;
                        }
                    }
                }
            }
        return true;
    }

    @Override
    public  Map<String, Object> getFinaFurl(String receiptType, String supplierId, String createTimeStart, String endTime,
								            String salesType, String code, String productName, 
								            Integer viceQtyStart,Integer viceQtyEnd,BigDecimal qtyStart,
								            BigDecimal qtyEnd, BigDecimal unitPriceStart, BigDecimal unitPriceEnd,
								            BigDecimal totalPriceStart, BigDecimal totalPriceEnd, BigDecimal totalAmountStart,
								            BigDecimal totalAmountEnd, BigDecimal hxPriceStart, BigDecimal hxPriceEnd,
								            BigDecimal zkPriceStart, BigDecimal zkPriceEnd, BigDecimal qkPriceStart,
								            BigDecimal qkPriceEnd, String remark) {

    	List<FinaFurlDTO> list = null;
    	if(StringUtils.equals("1", receiptType)) {
    		list = this.baseMapper.getQCFinaFurlDTO(supplierId, createTimeStart, salesType, code, 
    				productName, viceQtyStart, viceQtyEnd, qtyStart, qtyEnd, unitPriceStart, unitPriceEnd, totalPriceStart,
    				totalPriceEnd, totalAmountStart, totalAmountEnd, hxPriceStart, hxPriceEnd,
    				zkPriceStart, zkPriceEnd, qkPriceStart, qkPriceEnd,remark);
    	}
//    	else if(StringUtils.equals("2", receiptType)){
//    		list = this.baseMapper.getFinaFurlDTO(supplierId,createTimeStart,endTime
//                    ,"0",code,productName,qtyStart,
//                    qtyEnd,unitPriceStart,unitPriceEnd,totalPriceStart,totalPriceEnd,totalAmountStart,
//                    totalAmountEnd,hxPriceStart,hxPriceEnd,zkPriceStart,zkPriceEnd,qkPriceStart,
//                    qkPriceEnd,remark);
//    	}
    	else {
    		list = this.baseMapper.getFinaFurlDTO(supplierId,createTimeStart,endTime
                    ,salesType,code,productName,viceQtyStart, viceQtyEnd,qtyStart,
                    qtyEnd,unitPriceStart,unitPriceEnd,totalPriceStart,totalPriceEnd,totalAmountStart,
                    totalAmountEnd,hxPriceStart,hxPriceEnd,zkPriceStart,zkPriceEnd,qkPriceStart,
                    qkPriceEnd,remark);
    	}

        Map<String, String> dictItemMap = getDictMap("receiptType");
        if(CollUtil.isNotEmpty(list)) {
        	for (FinaFurlDTO vo : list) {
				String type = vo.getSalesType();
				if(oConvertUtils.isNotEmpty(type)) {
					String text = dictItemMap.get(type.toString());
					if(oConvertUtils.isNotEmpty(text)) {
						vo.setSalesType_dictText(text);
					}
				}
			}
        }
        
        /********************去除list中code重复的数据*****************************/
        ArrayList<FinaFurlDTO> newList = list.stream().collect
                (Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(FinaFurlDTO::getCode))), ArrayList::new));
        /*********************************************************************/
        FinaPaymentPage receiptPage = this.finaPaymentMapper.getTotalOwed(supplierId, null, createTimeStart);
        FinaFurlDTO entryVO = new FinaFurlDTO();
        entryVO.setProductName("期初欠款");
        BigDecimal decimal = receiptPage.getTotalOwed().subtract(receiptPage.getPaids());
        if (receiptPage != null) {
            entryVO.setQkPrice(decimal);//期初欠款
        }
//        list.add(0,entryVO);

        BigDecimal vq = new BigDecimal("0");
        BigDecimal qty = new BigDecimal("0");
        BigDecimal tp = new BigDecimal("0");//金额
        BigDecimal hp = new BigDecimal("0");//收款金额
        List<String> codeList = Lists.newArrayList();
        if(StringUtils.equals("1", receiptType)) {
        	for (FinaFurlDTO orEntryVO : list) {
        		orEntryVO.setQkPrice(orEntryVO.getTotalPrice().subtract(orEntryVO.getHxPrice()));
        		vq=vq.add(orEntryVO.getViceQty());
        		hp=hp.add(orEntryVO.getHxPrice());
        		qty=qty.add(orEntryVO.getQty());
        		tp=tp.add(orEntryVO.getTotalPrice());
        	}
        }else {
        	BigDecimal dj = BigDecimal.ZERO;//单据金额
        	for (FinaFurlDTO orEntryVO : list) {
        		if(!codeList.contains(orEntryVO.getCode()) && StringUtils.equals("0", orEntryVO.getSalesType())) {
        			decimal=decimal.subtract(orEntryVO.getZkPrice());
        		}
            	if(orEntryVO.getSalesType()!=null && StringUtils.equals("0", orEntryVO.getSalesType())){
                    orEntryVO.setQkPrice(orEntryVO.getTotalPrice());
                }
                if(orEntryVO.getSalesType()!=null && StringUtils.equals("0", orEntryVO.getSalesType())){
                    orEntryVO.setHxPrice(new BigDecimal("0"));
                }
                if( orEntryVO.getHxPrice() != null && orEntryVO.getHxPrice().compareTo(BigDecimal.ZERO)>0){
                    hp=hp.add(orEntryVO.getHxPrice());
                }
                if(orEntryVO.getViceQty() != null && orEntryVO.getViceQty().compareTo(BigDecimal.ZERO)>0){
                    vq=vq.add(orEntryVO.getViceQty());
                }
                if(orEntryVO.getQty() != null && orEntryVO.getQty().compareTo(BigDecimal.ZERO)>0){
                    qty=qty.add(orEntryVO.getQty());
                }
                if(orEntryVO.getTotalPrice() != null && orEntryVO.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
                    tp=tp.add(orEntryVO.getTotalPrice());
                }

                if(orEntryVO.getSalesType()!=null && StringUtils.equals("0", orEntryVO.getSalesType())){
                    decimal=decimal.add(orEntryVO.getTotalPrice());
                    orEntryVO.setQkPrice(decimal);
                    dj = orEntryVO.getTotalAmount();
                }
                if(StringUtils.equals("1", orEntryVO.getSalesType())) {
                    decimal=decimal.subtract(orEntryVO.getHxPrice());
                    orEntryVO.setTotalAmount(dj);
                    orEntryVO.setQkPrice(decimal);
                }
                codeList.add(orEntryVO.getCode());
            }
        }
        FinaFurlDTO entryVO1 = new FinaFurlDTO();
        String date="";
        if(StringUtils.isNotBlank(createTimeStart)) {
            StringBuffer buffer = new StringBuffer();
            String[] s = createTimeStart.split("-");
            buffer.append(s[0]);
            buffer.append("年");
            buffer.append(s[1]);
            buffer.append("月");
            date = buffer.toString();
        }else{
            date= DateUtils.formatDate(new Date(),"yyyy年MM月");
        }


        entryVO1.setProductName(date+"合计");
        entryVO1.setTotalPrice(tp);
        entryVO1.setHxPrice(hp);
//        list.add(list.size(),entryVO1);
        /**集合最后一个位置数据添加*/

        FinaFurlDTO entryVO2 = new FinaFurlDTO();
        entryVO2.setCode("单据数:"+newList.size());
        entryVO2.setProductName("总合计");
        entryVO2.setViceQty(vq);
        entryVO2.setQty(qty);
        entryVO2.setTotalPrice(tp);
        entryVO2.setHxPrice(hp);
        entryVO2.setQkPrice(decimal);//欠款金额
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("total", entryVO2);//合计
        list.add(0, entryVO);//初期欠款
        map.put("settlement", entryVO);//初期结款
        map.put("list", list);//列表
//        list.add(list.size(),entryVO2);
        return map;
	}
    
    private Map<String, String> getDictMap(String dictCode){
		List<DictModel> items = sysBasApi.queryDictItemsByCode(dictCode);
        Map<String, String> dictItemMap = Maps.newHashMap();
        if(CollUtil.isNotEmpty(items)) {
        	for (DictModel model : items) {
        		String value = model.getValue();
        		String text = model.getText();
        		dictItemMap.put(value, text);
			}
        }
        return dictItemMap;
	}

	@Override
	public IPage<FinaPayment> paymentList(Page<FinaPayment> page, HttpServletRequest req) {
		String createTimeStartStr = req.getParameter("createTimeStart");
		String createTimeEndStr = req.getParameter("createTimeEnd");
		String supplierName = req.getParameter("supplierName");
		Date createTimeStart = null;
		Date createTimeEnd = null;
		if(StringUtils.isNotBlank(createTimeStartStr)) {
			createTimeStart = DateUtil.parseDate(createTimeStartStr);
		}
		if(StringUtils.isNotBlank(createTimeEndStr)) {
			createTimeEnd = DateUtil.parseDate(createTimeEndStr);
			Calendar calendar = CalendarUtil.calendar(createTimeEnd);
			calendar.add(Calendar.DAY_OF_YEAR, 1);
			createTimeEnd = calendar.getTime();
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("supplierName", supplierName);
		map.put("createTimeStart", createTimeStart);
		map.put("createTimeEnd", createTimeEnd);
		
		//添加查询条件
		String orderNo = req.getParameter("orderNo");
    	String clearingForm = req.getParameter("clearingForm");
    	String amountStart = req.getParameter("amountStart");
    	String amountEnd = req.getParameter("amountEnd");
    	String discountStart = req.getParameter("discountStart");
    	String discountEnd = req.getParameter("discountEnd");
    	map.put("orderNo", orderNo);
    	map.put("clearingForm", clearingForm);
    	if(StringUtils.isNotBlank(amountStart)) {
    		try {
				BigDecimal decimal = new BigDecimal(amountStart);
				map.put("amountStart", decimal);
			} catch (Exception e) {
				map.put("amountStart", null);
			}
    	}
		if(StringUtils.isNotBlank(amountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(amountEnd);
				map.put("amountEnd", decimal);
			} catch (Exception e) {
				map.put("amountEnd", null);
			}
		}
		if(StringUtils.isNotBlank(discountStart)) {
			try {
				BigDecimal decimal = new BigDecimal(discountStart);
				map.put("discountStart", decimal);
			} catch (Exception e) {
				map.put("discountStart", null);
			}
		}
		if(StringUtils.isNotBlank(discountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(discountEnd);
				map.put("discountEnd", decimal);
			} catch (Exception e) {
				map.put("discountEnd", null);
			}
		}
		// 排序
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		System.out.println(column);
		if(StringUtils.isNotBlank(column)) {
			map.put("orderFlag", Boolean.TRUE);
			StringBuffer buffer = new StringBuffer(" order by ");
			if(column.equals("code")) {
				buffer.append(" fina_payment.code ");
			} else if (column.equals("supplierName")) {
				buffer.append(" bas_supplier.name ");
			} else if (column.equals("clearingForm_dictText")) {
				buffer.append(" fina_payment.clearing_form ");
			} else if (column.equals("payTime")) {
				buffer.append(" fina_payment.pay_time ");
			} else if (column.equals("price")) {
				buffer.append(" fina_payment.price ");
			} else if (column.equals("discountPrice")) {
				buffer.append(" fina_payment.discount_price ");
			} else if (column.equals("createTime")) {
				buffer.append(" fina_payment.create_time ");
			}
			
			buffer.append(" ").append(order).append(" ");
			map.put("orderStr", buffer.toString());
			
		} else {
			map.put("orderFlag", Boolean.FALSE);
		}
		
		IPage<FinaPayment> list = this.baseMapper.paymentList(page, map);
		List<FinaPayment> payments = list.getRecords();
		if(CollUtil.isNotEmpty(payments)) {
			List<String> paymentIds = Lists.newArrayList();
			for (FinaPayment finaPayment : payments) {
				paymentIds.add(finaPayment.getId());
			}
			//TODO
			List<FinaPaymentEntryLk> entryLks = lkService.lambdaQuery().in(FinaPaymentEntryLk::getPaymentId, paymentIds).list();
			if(CollUtil.isNotEmpty(entryLks)) {
				Map<String, BigDecimal> pamentHxPriceMap = Maps.newHashMap();
				for (FinaPaymentEntryLk lk : entryLks) {
					String paymentId = lk.getPaymentId();
					BigDecimal discountAmount = lk.getDiscountAmount() == null ? BigDecimal.ZERO : lk.getDiscountAmount();
					BigDecimal entryMoney = lk.getEntryMoney() == null ? BigDecimal.ZERO : lk.getEntryMoney();
					BigDecimal total = discountAmount.add(entryMoney);
					BigDecimal decimal = pamentHxPriceMap.get(paymentId);
					if(decimal == null) {
						pamentHxPriceMap.put(paymentId, total);
					} else {
						decimal = decimal.add(total);
						pamentHxPriceMap.put(paymentId, decimal);
					}
				}
				for (FinaPayment finaPayment : payments) {
					String id = finaPayment.getId();
					BigDecimal hxPrice = pamentHxPriceMap.get(id);
					if(hxPrice == null) {
						hxPrice = BigDecimal.ZERO;
					}
					finaPayment.setHxPrice(hxPrice);
				}
			}
		}
		return list;
	}

	@Override
	public List<ReceiveDTO> getSupplierReceive(String supplierId) {
		List<ReceiveDTO> list = this.baseMapper.getSupplierReceive(supplierId);
		if(CollUtil.isNotEmpty(list)) {
			BigDecimal sum = BigDecimal.ZERO;
			for (ReceiveDTO receive : list) {
				BigDecimal payAmount = receive.getPayAmount() == null ? BigDecimal.ZERO : receive.getPayAmount();
				BigDecimal totalPrice = receive.getTotalPrice() == null ? BigDecimal.ZERO : receive.getTotalPrice();
				BigDecimal restAmount = totalPrice.subtract(payAmount);
				receive.setUnPayAmount(restAmount);
				BigDecimal unPayAmount = receive.getUnPayAmount();
				receive.setEntryAmount(BigDecimal.ZERO);
				sum = sum.add(unPayAmount);
				receive.setSummary(sum);
				receive.setWriteAmount(payAmount);
				receive.setPayAmount(BigDecimal.ZERO);
			}
		}
		return list;
	}

	@Override
	@Transactional
	public Result<?> addPayment(PaymentVO paymentVO) {
		// TODO Auto-generated method stub
		synchronized (paymentVO) {
			List<ReceiveDTO> entryList = paymentVO.getEntryIdList();
//			if(CollUtil.isEmpty(entryList)) {
//				return Result.error("请选择收货明细");
//			}
			List<String> entryIds = CollUtil.newArrayList(UUID.randomUUID().toString());
			List<String> furlIds = CollUtil.newArrayList(UUID.randomUUID().toString());
			for (ReceiveDTO receiveDTO : entryList) {
				entryIds.add(receiveDTO.getId());
				furlIds.add(receiveDTO.getMid());
			}
			List<FinaFurlEntry> furlEntryList = furlEntryService.lambdaQuery().in(FinaFurlEntry::getId, entryIds).list();
//			if(CollUtil.isEmpty(furlEntryList)) {
//				return Result.error("请选择收货明细");
//			}
			List<FinaFurl> furlList = finaFurlService.lambdaQuery().in(FinaFurl::getId, furlIds).list();
//			if(CollUtil.isEmpty(furlList)) {
//				return Result.error("未找到收货单信息");
//			}
			BigDecimal totalEntryAmount = BigDecimal.ZERO;
			for (FinaFurlEntry entry : furlEntryList) {
				BigDecimal payAmount = entry.getPayAmount();
				BigDecimal totalPrice = entry.getTotalPrice();
				if(null == totalPrice) {
					totalPrice = BigDecimal.ZERO;
				}
				if(null == payAmount) {
					payAmount = BigDecimal.ZERO;
				}
				BigDecimal amount = totalPrice.subtract(payAmount);
				totalEntryAmount = totalEntryAmount.add(amount);
			}
			BigDecimal price = paymentVO.getPrice();
			BigDecimal discountPrice = paymentVO.getDiscountPrice();
			if(null == discountPrice) {
				discountPrice = BigDecimal.ZERO;
			}
			BigDecimal totalPrice = price.add(discountPrice);
//			if(totalPrice.compareTo(totalEntryAmount) > 0) {
//				return Result.error("金额大于选中的收货明细的金额");
//			}
			
			FinaPayment payment = new FinaPayment();
			String payTimeStr = paymentVO.getPayTime();
			Date payTime = null;
			if(StringUtils.isBlank(payTimeStr)) {
				payTime = DateUtil.date();
			} else {
				payTime = DateUtil.parseDate(payTimeStr);
			}
			payment.setPayTime(payTime);
			payment.setAccountId(paymentVO.getAccountId());
			String code = this.sysBasApi.getNoByCode("cw_fk_no");
			payment.setCode(code);
			if(null != paymentVO.getIsHX()) {
				payment.setIsHx(paymentVO.getIsHX().toString());
			}
			payment.setPrice(price);
			payment.setDiscountPrice(discountPrice);
			payment.setClearingForm(paymentVO.getClearingForm());
			payment.setRemark(paymentVO.getRemark());
			String supplierId = paymentVO.getSupplierId();
			String supplierName = null;
			payment.setSupplierId(supplierId);
			payment.setBillType("2");
			BasSupplier supplier = supplierService.getById(supplierId);
			if(null != supplier) {
				payment.setSupplierName(supplier.getName());
				supplierName = supplier.getName();
			}
			payment.setInvoicePrice(BigDecimal.ZERO);
			payment.setNoneInvoicePrice(payment.getPrice());
			boolean bl = this.save(payment);
			if(bl) {
				FinaFurl ff = new FinaFurl();
				ff.setSupplierId(supplierId);
				ff.setSupplierName(supplierName);
				ff.setShippingDate(DateUtil.date());
		        String name = userService.getUserNameByPhone(payment.getCreateBy());
		        ff.setMaker(name);
		        ff.setSalesType("1");
		        ff.setTotalAmount(BigDecimal.ZERO);
		        String capitalPrice = "0";
		        ff.setCapitalPrice(capitalPrice);
		        ff.setCode(payment.getCode());
		        ff.setRemark(payment.getRemark());
		        ff.setHxPrice(payment.getPrice());
		        ff.setZkPrice(payment.getDiscountPrice());
				this.finaFurlService.save(ff);
			}
			if(totalEntryAmount.compareTo(BigDecimal.ZERO) > 0) {
				Map<String, FinaFurl> furlMap = Maps.newLinkedHashMap();
				for (FinaFurl finaFurl : furlList) {
					furlMap.put(finaFurl.getId(), finaFurl);
				}
				BigDecimal totalMoney = totalPrice;
				List<FinaPaymentEntryLk> lkList = Lists.newArrayList();
				BigDecimal theDiscountPrice = discountPrice;
				for (FinaFurlEntry furlEntry : furlEntryList) {
					BigDecimal payAmount = furlEntry.getPayAmount();
					if(payAmount == null) {
						payAmount = BigDecimal.ZERO;
					}
					BigDecimal entryPrice = furlEntry.getTotalPrice();
					BigDecimal leftPrice = entryPrice.subtract(payAmount);
					FinaPaymentEntryLk lk = new FinaPaymentEntryLk();
					lk.setPaymentId(payment.getId());
					lk.setEntryId(furlEntry.getId());
					lk.setFurlId(furlEntry.getMid());
					if(totalMoney.compareTo(leftPrice) < 0) {
						furlEntry.setPayAmount(payAmount.add(totalMoney));
						furlEntry.setPayStatus("1");
						this.furlEntryService.updateById(furlEntry);
						
						if(theDiscountPrice.compareTo(BigDecimal.ZERO) > 0) {
							if(theDiscountPrice.compareTo(leftPrice) > 0) {
								lk.setEntryMoney(BigDecimal.ZERO);
								lk.setDiscountAmount(totalMoney);
							} else {
								lk.setEntryMoney(totalMoney.subtract(theDiscountPrice));
								lk.setDiscountAmount(theDiscountPrice);
							}
						} else {
							lk.setEntryMoney(totalMoney);
							lk.setDiscountAmount(BigDecimal.ZERO);
						}
						lk.setPayStatus("1");
						lkList.add(lk);
						break;
					} else {
						furlEntry.setPayAmount(entryPrice);
						furlEntry.setPayStatus("2");
						this.furlEntryService.updateById(furlEntry);
						
						totalMoney = totalMoney.subtract(leftPrice);
						if(theDiscountPrice.compareTo(BigDecimal.ZERO) > 0) {
							if(theDiscountPrice.compareTo(leftPrice) > 0) {
								lk.setEntryMoney(BigDecimal.ZERO);
								lk.setDiscountAmount(leftPrice);
								theDiscountPrice = theDiscountPrice.subtract(leftPrice);
							} else {
								lk.setEntryMoney(leftPrice.subtract(theDiscountPrice));
								lk.setDiscountAmount(theDiscountPrice);
								theDiscountPrice = BigDecimal.ZERO;
							}
						} else {
							lk.setEntryMoney(leftPrice);
							lk.setDiscountAmount(BigDecimal.ZERO);
						}
						lk.setPayStatus("2");
						lkList.add(lk);
					}
				}
				this.lkService.saveBatch(lkList);
				for (FinaFurl furl : furlList) {
					String id = furl.getId();
					BigDecimal hxPrice = furl.getHxPrice();
					if(null == hxPrice) {
						hxPrice = BigDecimal.ZERO;
					}
					BigDecimal zkPrice = furl.getZkPrice();
					if(null == zkPrice) {
						zkPrice = BigDecimal.ZERO;
					}
					BigDecimal totalAmount = furl.getTotalAmount();
					if(null == totalAmount) {
						totalAmount = BigDecimal.ZERO;
					}
					for (FinaPaymentEntryLk lk : lkList) {
						if(lk.getFurlId().equals(id)) {
							BigDecimal discountAmount = lk.getDiscountAmount();
							BigDecimal entryMoney = lk.getEntryMoney();
							if(discountAmount.compareTo(BigDecimal.ZERO) > 0) {
								zkPrice = zkPrice.add(discountAmount);
							}
							if(entryMoney.compareTo(BigDecimal.ZERO) > 0) {
								hxPrice = hxPrice.add(entryMoney);
							}
							if(zkPrice.add(hxPrice).compareTo(totalAmount) > 0) {
								throw new JeecgBootException("金额填写有误");
							}
							furl.setZkPrice(zkPrice);
							furl.setHxPrice(hxPrice);
						}
					}
					if(zkPrice.add(hxPrice).compareTo(totalAmount) == 0) {
						furl.setHxType("2");
					} else {
						furl.setHxType("1");
					}
					this.finaFurlService.updateById(furl);
				}
			}
			return Result.ok("成功");
		}
	}

	@Override
	public Result<?> updatePayment(PaymentVO paymentVO) {
		// TODO Auto-generated method stub\
		String pamentId = paymentVO.getId();
		synchronized (paymentVO) {
			List<ReceiveDTO> entryList = paymentVO.getEntryIdList();
//			if(CollUtil.isEmpty(entryList)) {
//				return Result.error("请选择收货明细");
//			}
			List<String> entryIds = CollUtil.newArrayList(UUID.randomUUID().toString());
			List<String> furlIds = CollUtil.newArrayList(UUID.randomUUID().toString());
			for (ReceiveDTO receiveDTO : entryList) {
				entryIds.add(receiveDTO.getId());
				furlIds.add(receiveDTO.getMid());
			}
			List<FinaFurlEntry> furlEntryList = furlEntryService.lambdaQuery().in(FinaFurlEntry::getId, entryIds).list();
//			if(CollUtil.isEmpty(furlEntryList)) {
//				return Result.error("请选择收货明细");
//			}
			List<FinaFurl> furlList = finaFurlService.lambdaQuery().in(FinaFurl::getId, furlIds).list();
			Map<String,String> map = Maps.newHashMap();
			if(CollUtil.isNotEmpty(furlList)) {
				for(FinaFurl furl:furlList) {
					map.put(furl.getId(), furl.getIsInvoice());
				}
			}
			List<FinaPaymentEntryLk> oldLkList = lkService.lambdaQuery().eq(FinaPaymentEntryLk::getPaymentId, pamentId).list();
			Map<String, FinaPaymentEntryLk> oldLkMap = Maps.newHashMap();
			for (FinaPaymentEntryLk lk : oldLkList) {
				oldLkMap.put(lk.getEntryId(), lk);
			}
			BigDecimal totalEntryAmount = BigDecimal.ZERO;
			BigDecimal invoice = BigDecimal.ZERO;
			for (FinaFurlEntry entry : furlEntryList) {
				BigDecimal payAmount = entry.getPayAmount();
				BigDecimal totalPrice = entry.getTotalPrice();
				if(null == totalPrice) {
					totalPrice = BigDecimal.ZERO;
				}
				if(null == payAmount) {
					payAmount = BigDecimal.ZERO;
				}
				//记录需开票的收货金额
				if(StringUtils.equals("1", map.get(entry.getMid()))) {
					invoice = invoice.add(totalPrice);
				}
				FinaPaymentEntryLk lk = oldLkMap.get(entry.getId());
				if(null == lk) {
					BigDecimal amount = totalPrice.subtract(payAmount);
					totalEntryAmount = totalEntryAmount.add(amount);
				} else {
					BigDecimal discountAmount = lk.getDiscountAmount() == null ? BigDecimal.ZERO : lk.getDiscountAmount();
					BigDecimal entryMoney = lk.getEntryMoney() == null ? BigDecimal.ZERO : lk.getEntryMoney();
					BigDecimal amount = totalPrice.subtract(payAmount).add(discountAmount).add(entryMoney);
					totalEntryAmount = totalEntryAmount.add(amount);
				}
			}
			BigDecimal price = paymentVO.getPrice();
			BigDecimal discountPrice = paymentVO.getDiscountPrice();
			if(null == discountPrice) {
				discountPrice = BigDecimal.ZERO;
			}
			BigDecimal totalPrice = price.add(discountPrice);
//			if(totalPrice.compareTo(totalEntryAmount) > 0) {
//				return Result.error("金额大于选中的收货明细的金额");
//			}
			//清除以前的信息
			List<String> oldIkIds = Lists.newArrayList();
			if(CollUtil.isNotEmpty(oldLkList)) {
				for (FinaPaymentEntryLk lk : oldLkList) {
					String entryId = lk.getEntryId();
					BigDecimal discountAmount = lk.getDiscountAmount() == null ? BigDecimal.ZERO : lk.getDiscountAmount();
					String furlId = lk.getFurlId();
					BigDecimal entryMoney = lk.getEntryMoney() == null ? BigDecimal.ZERO : lk.getEntryMoney();
					BigDecimal totalLkAmount = discountAmount.add(entryMoney);
					
					FinaFurlEntry furlEntry = this.furlEntryService.getById(entryId);
					if(furlEntry != null) {
						BigDecimal payAmount = furlEntry.getPayAmount() == null ? BigDecimal.ZERO : furlEntry.getPayAmount();
						payAmount = payAmount.subtract(totalLkAmount);
						furlEntry.setPayAmount(payAmount);
						if(payAmount.compareTo(BigDecimal.ZERO) < 0) {
							throw new JeecgBootException("数值输入错误!");
						}
						if(payAmount.compareTo(BigDecimal.ZERO) < 0) {
							furlEntry.setPayStatus("0");
						}
						if(payAmount.compareTo(BigDecimal.ZERO) > 0) {
							furlEntry.setPayStatus("1");
						}
						this.furlEntryService.updateById(furlEntry);
					}
					FinaFurl furl = this.finaFurlService.getById(furlId);
					if(null != furl) {
						BigDecimal hxPrice = furl.getHxPrice() == null ? BigDecimal.ZERO : furl.getHxPrice();
						BigDecimal zkPrice = furl.getZkPrice() == null ? BigDecimal.ZERO : furl.getZkPrice();
						
						hxPrice = hxPrice.subtract(entryMoney);
						zkPrice = zkPrice.subtract(discountAmount);
						if(hxPrice.compareTo(BigDecimal.ZERO) < 0 || zkPrice.compareTo(BigDecimal.ZERO) < 0) {
							throw new JeecgBootException("数值输入错误!!");
						}
						furl.setHxPrice(hxPrice);
						furl.setZkPrice(zkPrice);
						if(hxPrice.compareTo(BigDecimal.ZERO) == 0 && zkPrice.compareTo(BigDecimal.ZERO) == 0) {
							furl.setHxType("0");
						} else {
							furl.setHxType("1");
						}
						
						this.finaFurlService.updateById(furl);
					}
					oldIkIds.add(lk.getId());
				}
				this.lkService.removeByIds(oldIkIds);
			}
			
			FinaPayment payment = this.getById(pamentId);
			if(payment == null) {
				return Result.error("未找到要修改的付款单");
			}
			payment.setAccountId(paymentVO.getAccountId());
			if(null != paymentVO.getIsHX()) {
				payment.setIsHx(paymentVO.getIsHX().toString());
			}
			String payTimeStr = paymentVO.getPayTime();
			Date payTime = null;
			if(StringUtils.isBlank(payTimeStr)) {
				payTime = DateUtil.date();
			} else {
				payTime = DateUtil.parseDate(payTimeStr);
			}
			payment.setPayTime(payTime);
			payment.setPrice(price);
			payment.setId(pamentId);
			payment.setDiscountPrice(discountPrice);
			payment.setClearingForm(paymentVO.getClearingForm());
			payment.setRemark(paymentVO.getRemark());
			BigDecimal invoicePrice = payment.getInvoicePrice() == null ? BigDecimal.ZERO : payment.getInvoicePrice();
			payment.setNoneInvoicePrice(invoice.subtract(invoicePrice));
			boolean saveFlag = this.updateById(payment);
			if(saveFlag) {
				LambdaQueryWrapper<FinaFurl> query = new LambdaQueryWrapper<>();
				query.eq(FinaFurl::getCode, payment.getCode());
				List<FinaFurl> ffList = this.finaFurlService.list(query);
				if(CollUtil.isNotEmpty(ffList)) {
					FinaFurl ff = ffList.get(0);
					ff.setSalesType("1");
			        ff.setTotalAmount(BigDecimal.ZERO);
			        ff.setRemark(payment.getRemark());
			        ff.setHxPrice(payment.getPrice());
			        ff.setZkPrice(payment.getDiscountPrice());
					this.finaFurlService.updateById(ff);
				}
			}
			if (totalEntryAmount.compareTo(BigDecimal.ZERO) > 0) {
				Map<String, FinaFurl> furlMap = Maps.newLinkedHashMap();
				for (FinaFurl finaFurl : furlList) {
					furlMap.put(finaFurl.getId(), finaFurl);
				}
				BigDecimal totalMoney = totalPrice;
				List<FinaPaymentEntryLk> lkList = Lists.newArrayList();
				BigDecimal theDiscountPrice = discountPrice;
				for (FinaFurlEntry furlEntry : furlEntryList) {
					BigDecimal payAmount = furlEntry.getPayAmount();
					if(payAmount == null) {
						payAmount = BigDecimal.ZERO;
					}
					BigDecimal entryPrice = furlEntry.getTotalPrice();
					BigDecimal leftPrice = entryPrice.subtract(payAmount);
					FinaPaymentEntryLk lk = new FinaPaymentEntryLk();
					lk.setPaymentId(payment.getId());
					lk.setEntryId(furlEntry.getId());
					lk.setFurlId(furlEntry.getMid());
					if(totalMoney.compareTo(leftPrice) < 0) {
						furlEntry.setPayAmount(payAmount.add(totalMoney));
						furlEntry.setPayStatus("1");
						this.furlEntryService.updateById(furlEntry);
						
						if(theDiscountPrice.compareTo(BigDecimal.ZERO) > 0) {
							if(theDiscountPrice.compareTo(leftPrice) > 0) {
								lk.setEntryMoney(BigDecimal.ZERO);
								lk.setDiscountAmount(leftPrice);
							} else {
								lk.setEntryMoney(totalMoney.subtract(theDiscountPrice));
								lk.setDiscountAmount(theDiscountPrice);
							}
						} else {
							lk.setEntryMoney(totalMoney);
							lk.setDiscountAmount(BigDecimal.ZERO);
						}
						lk.setPayStatus("1");
						lkList.add(lk);
						break;
					} else {
						furlEntry.setPayAmount(entryPrice);
						furlEntry.setPayStatus("2");
						this.furlEntryService.updateById(furlEntry);
						
						totalMoney = totalMoney.subtract(leftPrice);
						if(theDiscountPrice.compareTo(BigDecimal.ZERO) > 0) {
							if(theDiscountPrice.compareTo(leftPrice) > 0) {
								lk.setEntryMoney(BigDecimal.ZERO);
								lk.setDiscountAmount(leftPrice);
								theDiscountPrice = theDiscountPrice.subtract(leftPrice);
							} else {
								lk.setEntryMoney(leftPrice.subtract(theDiscountPrice));
								lk.setDiscountAmount(theDiscountPrice);
								theDiscountPrice = BigDecimal.ZERO;
							}
						} else {
							lk.setEntryMoney(leftPrice);
							lk.setDiscountAmount(BigDecimal.ZERO);
						}
						lk.setPayStatus("2");
						lkList.add(lk);
					}
				}
				this.lkService.saveBatch(lkList);
				for (FinaFurl furl : furlList) {
					String id = furl.getId();
					BigDecimal hxPrice = furl.getHxPrice();
					if(null == hxPrice) {
						hxPrice = BigDecimal.ZERO;
					}
					BigDecimal zkPrice = furl.getZkPrice();
					if(null == zkPrice) {
						zkPrice = BigDecimal.ZERO;
					}
					BigDecimal totalAmount = furl.getTotalAmount();
					if(null == totalAmount) {
						totalAmount = BigDecimal.ZERO;
					}
					for (FinaPaymentEntryLk lk : lkList) {
						if(lk.getFurlId().equals(id)) {
							BigDecimal discountAmount = lk.getDiscountAmount();
							BigDecimal entryMoney = lk.getEntryMoney();
							if(discountAmount.compareTo(BigDecimal.ZERO) > 0) {
								zkPrice = zkPrice.add(discountAmount);
							}
							if(entryMoney.compareTo(BigDecimal.ZERO) > 0) {
								hxPrice = hxPrice.add(entryMoney);
							}
							if(zkPrice.add(hxPrice).compareTo(totalAmount) > 0) {
								throw new JeecgBootException("金额填写有误");
							}
							furl.setZkPrice(zkPrice);
							furl.setHxPrice(hxPrice);
						}
					}
					if(zkPrice.add(hxPrice).compareTo(totalAmount) == 0) {
						furl.setHxType("2");
					} else {
						furl.setHxType("1");
					}
					this.finaFurlService.updateById(furl);
				}
			}
			return Result.ok("成功");
		}
	}

	@Override
	public Result<PaymentVO> getPaymentInfo(String paymentId) {
		// TODO Auto-generated method stub
		Result<PaymentVO> result = new Result<>();
		FinaPayment payment = this.getById(paymentId);
		if(null == payment) {
			return result.error500("未找到相关的付款单");
		}
		PaymentVO vo = new PaymentVO();
		vo.setId(payment.getId());
		String accountId = payment.getAccountId();
		vo.setAccountId(accountId);
		BasBankAccount account = this.accountService.getById(accountId);
		if(null != account) {
			vo.setAccountNo(account.getAccountNo());
		}
		vo.setClearingForm(payment.getClearingForm());
		vo.setDiscountPrice(payment.getDiscountPrice());
		vo.setPrice(payment.getPrice());
		if(StringUtils.isNotBlank(payment.getIsHx())) {
			vo.setIsHX(Boolean.valueOf(payment.getIsHx()));
		}
		
		String supplierId = payment.getSupplierId();
		vo.setSupplierId(supplierId);
		BasSupplier supplier = this.supplierService.getById(supplierId);
		if(null != supplier) {
			vo.setSupplierName(supplier.getName());
		}
		List<FinaPaymentEntryLk> lkList = this.lkService.lambdaQuery().eq(FinaPaymentEntryLk::getPaymentId, paymentId).list();
		if(CollUtil.isNotEmpty(lkList)) {
			for (FinaPaymentEntryLk lk : lkList) {
				lk.setId(lk.getEntryId());
			}
		}
		vo.setLkList(lkList);
		
		List<ReceiveDTO> receives = this.getSupplierUpdateReceive(supplierId, lkList);
		vo.setEntryIdList(receives);
		result.setResult(vo);
		return result;
	}

	private List<ReceiveDTO> getSupplierUpdateReceive(String supplierId, List<FinaPaymentEntryLk> lkList){
		List<String> entryIds = Lists.newArrayList();
		for (FinaPaymentEntryLk finaPaymentEntryLk : lkList) {
			entryIds.add(finaPaymentEntryLk.getEntryId());
		}
		List<ReceiveDTO> list = this.baseMapper.getSupplierReceive(supplierId, entryIds);
		if(CollUtil.isNotEmpty(list)) {
			BigDecimal sum = BigDecimal.ZERO;
			for (ReceiveDTO receive : list) {
				BigDecimal payAmount = receive.getPayAmount() == null ? BigDecimal.ZERO : receive.getPayAmount();
				BigDecimal totalPrice = receive.getTotalPrice() == null ? BigDecimal.ZERO : receive.getTotalPrice();
				BigDecimal restAmount = totalPrice.subtract(payAmount);
				receive.setUnPayAmount(restAmount);
				String id = receive.getId();
				if(entryIds.contains(id)) {
					receive.setIsSelect(Boolean.TRUE);
				} else {
					receive.setIsSelect(Boolean.FALSE);
				}
				
				BigDecimal unPayAmount = receive.getUnPayAmount();
				if(null == unPayAmount) {
					unPayAmount = BigDecimal.ZERO;
				}
//				FinaReceiptEntryLk lk = lkMap.get(dto.getId());
//				if(lk != null && lk.getAmount() != null) {
//					sum = sum.add(lk.getAmount());
//				}
				for (FinaPaymentEntryLk lk : lkList) {
					String entryId = lk.getEntryId();
					if(entryId.equals(receive.getId())){
						receive.setPayAmount(lk.getDiscountAmount().add(lk.getEntryMoney()));
					}
				}
				sum = sum.add(unPayAmount);
				receive.setSummary(sum);
				receive.setWriteAmount(payAmount);
			}
		}
		return list;
	}
	
	/**
     * @Description: 收货汇总
     * @param finaFurlVO
     * @return
     * Create at: 2021-06-17 14:24:22
     * @author: xzs
     * Revision:
     *    2021-06-17 14:24:22 - first revision by xzs
     *
     */
	@Override
	public List<FinaFurlSumDTO> getFurlSum(FinaFurlVO finaFurlVO) {
		// TODO Auto-generated method stub
		String[] str=null;
        if(StringUtils.isNotBlank(finaFurlVO.getCategoryIds())) {
            str = finaFurlVO.getCategoryIds().split(",");
        }
        String field = finaFurlVO.getColumn();
        String order = finaFurlVO.getOrder();
        List<FinaFurlSumDTO> list=baseMapper.getFurlSumList(finaFurlVO.getCreateTimeStart(),finaFurlVO.getCreateTimeEnd(), str);
        FinaFurlSumDTO sum=baseMapper.getFurlSum(finaFurlVO.getCreateTimeStart(),finaFurlVO.getCreateTimeEnd(),str);
        for (FinaFurlSumDTO furlSum : list) {
            if(furlSum.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
                BigDecimal  decimal = furlSum.getTotalPrice().divide(furlSum.getQty(), 4, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                furlSum.setAverageUnitPrice(decimal);
                BigDecimal dec=furlSum.getTotalPrice().divide(sum.getPriceSum(),4, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                dec=dec.multiply(new BigDecimal("100"));
                furlSum.setPriceRatio(dec+"%");
            }
            if(furlSum.getQty().compareTo(BigDecimal.ZERO)>0){
                BigDecimal dec=furlSum.getQty().divide(sum.getQtySum(),4, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                dec=dec.multiply(new BigDecimal("100"));
                furlSum.setQtyRatio(dec+"%");
            }
        }
    	if(StringUtils.equals(field, "averageUnitPrice")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(FinaFurlSumDTO::getAverageUnitPrice));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(FinaFurlSumDTO::getAverageUnitPrice).reversed());
            }
    	}else if(StringUtils.equals(field, "qty")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(FinaFurlSumDTO::getQty));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(FinaFurlSumDTO::getQty).reversed());
            }
    	}else if(StringUtils.equals(field, "unit")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(FinaFurlSumDTO::getUnit));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(FinaFurlSumDTO::getUnit).reversed());
            }
    	}else if(StringUtils.equals(field, "totalPrice")) {
    		if(StringUtils.equals(order, "asc")) {
    			list.sort(Comparator.comparing(FinaFurlSumDTO::getTotalPrice));
            }else if(StringUtils.equals(order, "desc")) {
            	list.sort(Comparator.comparing(FinaFurlSumDTO::getTotalPrice).reversed());
            }
    	}
        return list;
	}

	@Override
	public List<FinaFurlEntryDTO> getFurlEntrySum(FinaFurlVO finaFurlVO) {
		// TODO Auto-generated method stub
        List<FinaFurlEntryDTO> list= baseMapper.getFurlEntrySum(finaFurlVO.getCreateTimeStart(),finaFurlVO.getCreateTimeEnd(),finaFurlVO.getCategoryName());
        List<FinaFurlEntryDTO> voList = Lists.newArrayList();
        List<String> customerIdList = Lists.newArrayList();
        FinaFurlEntryDTO vo = new FinaFurlEntryDTO();
        vo.setUnitPrice(BigDecimal.ZERO);
        vo.setSumPrice(BigDecimal.ZERO);
        vo.setViceQty(BigDecimal.ZERO);
        vo.setQty(BigDecimal.ZERO);
        int i = 0;
        for (FinaFurlEntryDTO deliverDetalidVO : list) {
        	++i;
        	
        	if(!customerIdList.contains(deliverDetalidVO.getSupplierId())&&customerIdList!=null&&customerIdList.size()>0) {
        		voList.add(vo);
        		vo = new FinaFurlEntryDTO();
        		vo.setUnitPrice(BigDecimal.ZERO);
                vo.setSumPrice(BigDecimal.ZERO);
                vo.setViceQty(BigDecimal.ZERO);
                vo.setQty(BigDecimal.ZERO);
        	}
        	vo.setCategoryName("小计");
    		vo.setSupplierName(deliverDetalidVO.getSupplierName());
    		vo.setSupplierId(deliverDetalidVO.getSupplierId());
//    		vo.setUnit(deliverDetalidVO.getUnit());
//    		vo.setUnitPrice(vo.getUnitPrice().add(deliverDetalidVO.getUnitPrice()));
            vo.setSumPrice(vo.getSumPrice().add(deliverDetalidVO.getSumPrice()));
            vo.setViceQty(vo.getViceQty().add(deliverDetalidVO.getViceQty()));
            vo.setQty(vo.getQty().add(deliverDetalidVO.getQty()));
        	customerIdList.add(deliverDetalidVO.getSupplierId());
        	voList.add(deliverDetalidVO);
        	if(list.size()==i) {
        		voList.add(vo);
        	}
        }
        return voList;
	}
	
	@Override
	@Transactional
	public void createPayable(StkIoBill stkIoBill, StkIoBillEntry entry) {
		String billNo = stkIoBill.getBillNo();
		List<FinaFurl> list = this.finaFurlService.lambdaQuery().eq(FinaFurl::getIoBillNo, billNo).list();
		if(CollUtil.isEmpty(list)) {
			List<StkIoBillEntry> entryList = Lists.newArrayList();
			entryList.add(entry);
			this.createPayable(stkIoBill, entryList);
			return;
		}
		FinaFurl furl = list.get(0);
		furl.setHxType("1");
		furl.setSalesType("0");
		//该收货单付款是否需要开发票
		furl.setIsInvoice(stkIoBill.getIsInvoice());
		FinaFurlEntry furlEntry = new FinaFurlEntry();
		BigDecimal amt = BigDecimal.ZERO;
		amt = amt.add(entry.getSettleAmt());
        BasMaterial material=materialService.getById(entry.getMaterialId());
        BasMaterialCategory category = materialCategoryService.getById(material.getCategoryId());
        furlEntry.setProductId(category.getId());
        furlEntry.setProductName(category.getName());
        furlEntry.setProductCode(category.getCode());
        furlEntry.setMaterialId(material.getId());
        furlEntry.setModel(material.getModel());
        furlEntry.setMid(furl.getId());
        furlEntry.setRemark(material.getRemark());
        furlEntry.setUnitPrice(entry.getSettlePrice());
        BasMeasureUnit unit=unitService.getById(entry.getUnitId());
        furlEntry.setUnit(unit.getName());
        furlEntry.setQty(entry.getQty());
        furlEntry.setTotalPrice(entry.getSettleAmt());
        furlEntry.setSalesType("0");
        furlEntry.setPayStatus("0");
        furlEntry.setPayAmount(BigDecimal.ZERO);
        this.furlEntryService.save(furlEntry);

        FinaPayment finaPayment=new FinaPayment();
        String suppName="";
        if(StringUtils.isNotBlank(stkIoBill.getSupplierId())){
            finaPayment.setSupplierId(stkIoBill.getSupplierId());
            BasSupplier basSupplier=supplierService.getById(stkIoBill.getSupplierId());
            if(basSupplier != null){
                suppName=basSupplier.getName();
                finaPayment.setSupplierName(suppName);
            }
        }
        String code = this.sysBasApi.getNoByCode("fh_no");
        finaPayment.setCode(code);
        finaPayment.setBillNo(stkIoBill.getSourceNo());
        finaPayment.setPrice(amt);
        finaPayment.setNoneInvoicePrice(amt);
        finaPayment.setBillType("3");//应付
//        save(finaPayment);

        BigDecimal totalAmount = furl.getTotalAmount() == null ? BigDecimal.ZERO : furl.getTotalAmount();
        totalAmount = totalAmount.add(furlEntry.getTotalPrice());
        furl.setTotalAmount(totalAmount);
        BigDecimal capitalDecimal = totalAmount.stripTrailingZeros();
        String capitalPrice = ZrkDeliverEntryServiceImpl.toChinese(capitalDecimal.toPlainString());
        furl.setCapitalPrice(capitalPrice);
        this.finaFurlService.updateById(furl);
	}

	@Override
	public Result<?> getPaymentStatistic(FinaPayment finaPayment, HttpServletRequest req) {
		// TODO Auto-generated method stub
		String createTimeStartStr = req.getParameter("createTimeStart");
		String createTimeEndStr = req.getParameter("createTimeEnd");
		String supplierName = req.getParameter("supplierName");
		Date createTimeStart = null;
		Date createTimeEnd = null;
		if(StringUtils.isNotBlank(createTimeStartStr)) {
			createTimeStart = DateUtil.parseDate(createTimeStartStr);
		}
		if(StringUtils.isNotBlank(createTimeEndStr)) {
			createTimeEnd = DateUtil.parseDate(createTimeEndStr);
			Calendar calendar = CalendarUtil.calendar(createTimeEnd);
			calendar.add(Calendar.DAY_OF_YEAR, 1);
			createTimeEnd = calendar.getTime();
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("supplierName", supplierName);
		map.put("createTimeStart", createTimeStart);
		map.put("createTimeEnd", createTimeEnd);
		
		//添加查询条件
		String orderNo = req.getParameter("orderNo");
    	String clearingForm = req.getParameter("clearingForm");
    	String amountStart = req.getParameter("amountStart");
    	String amountEnd = req.getParameter("amountEnd");
    	String discountStart = req.getParameter("discountStart");
    	String discountEnd = req.getParameter("discountEnd");
    	map.put("orderNo", orderNo);
    	map.put("clearingForm", clearingForm);
    	if(StringUtils.isNotBlank(amountStart)) {
    		try {
				BigDecimal decimal = new BigDecimal(amountStart);
				map.put("amountStart", decimal);
			} catch (Exception e) {
				map.put("amountStart", null);
			}
    	}
		if(StringUtils.isNotBlank(amountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(amountEnd);
				map.put("amountEnd", decimal);
			} catch (Exception e) {
				map.put("amountEnd", null);
			}
		}
		if(StringUtils.isNotBlank(discountStart)) {
			try {
				BigDecimal decimal = new BigDecimal(discountStart);
				map.put("discountStart", decimal);
			} catch (Exception e) {
				map.put("discountStart", null);
			}
		}
		if(StringUtils.isNotBlank(discountEnd)) {
			try {
				BigDecimal decimal = new BigDecimal(discountEnd);
				map.put("discountEnd", decimal);
			} catch (Exception e) {
				map.put("discountEnd", null);
			}
		}
		PaymentStatisticDTO ps = this.baseMapper.getPaymentStatistic(map);
		if(null == ps) {
			ps = new PaymentStatisticDTO();
		}
		ps.setDiscountPrice(ps.getDiscountPrice() == null ? BigDecimal.ZERO : ps.getDiscountPrice());
		ps.setSumPrice(ps.getSumPrice() == null ? BigDecimal.ZERO : ps.getSumPrice());
		ps.setTotalQuantity(ps.getTotalQuantity() == null ? BigDecimal.ZERO : ps.getTotalQuantity());
		return Result.ok(ps);
	}
}

